package mysqls

import (
	"qingbing/xzutils/structs"
	"qingbing/xzutils/utils"

	"gorm.io/gorm"
)

var tableNames = make(map[any]string, 0)

// 获取模型表名
func TableName(table any, gormDB ...*gorm.DB) string {
	var hashKey string
	if _, ok := table.(string); ok {
		hashKey = table.(string)
	} else {
		hashKey = structs.GetName(table)
	}
	if name, ok := tableNames[hashKey]; ok {
		return name
	} else {
		var tableName string
		if _, ok := table.(string); ok {
			tableName = table.(string)
		} else {
			ref := utils.GetReflectValue(table)
			method := ref.MethodByName("TableName")
			if method.IsValid() {
				tableName = method.Call(nil)[0].Interface().(string)
			} else {
				var stmt *gorm.Statement
				if len(gormDB) > 0 {
					stmt = gormDB[0].Model(table).Statement
				} else if DB != nil {
					stmt = DB.Model(table).Statement
				} else {
					panic("尚未给全局的 qingbing/xztools/mysqls.DB 赋值")
				}
				if err := stmt.Parse(table); err != nil {
					panic("解析 tablename 失败")
				}
				tableName = stmt.Table
			}
		}
		tableNames[hashKey] = tableName
		return tableName
	}
}
